﻿package newXgame.plane
{
	
	//////////////////////////////////////////////////////////////////
	import com.imvu.events.*;
	import com.imvu.widget.*;
	
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.external.ExternalInterface;
	import flash.geom.Point;
	import flash.utils.Timer;
	
	import org.dstart.object.debug.*;
	////////////////////////////////////////////////////////////////////
	
	public class Plane extends ClientWidget{
		
		private static const guestSign:String = "guest_";
		private static const FlashName:String = "feixingqi";
		private static const getAnsheIdUrl:String = "http://system.anshechung.com/0807/f_get_id.php";
		
		
		private static const redRoute:Array = ["blue4","red1","brown11","green8","blue5","red2","brown12","green9",
									  					  "blue6","red3","brown13","green10","blue7","red4","brown1","green11",
														   "blue8","red5","brown2","green12","blue9","red6","brown3","green13",
														  "blue10","red7","brown4","green1","blue11","red8","brown5","green2",
														  "blue12","red9","brown6","green3","blue13","red10","brown7","green4",
														  "blue1","red11","brown8","green5","blue2","red12","brown9","green6",
														  "blue3","red13","red14","red15","red16","red17","red18","redEnd"];
		
		private static const blueRoute:Array = ["green4","blue1","red11","brown8","green5","blue2","red12","brown9",
									   					   "green6","blue3","red13","brown10","green7","blue4","red1","brown11",
														   "green8","blue5","red2","brown12","green9","blue6","red3","brown13",
														   "green10","blue7","red4","brown1","green11","blue8","red5","brown2",
														   "green12","blue9","red6","brown3","green13","blue10","red7","brown4",
														   "green1","blue11","red8","brown5","green2","blue12","red9","brown6",
														   "green3","blue13","blue14","blue15","blue16","blue17","blue18","blueEnd"];
		
		private static const brownRoute:Array = ["red4","brown1","green11","blue8","red5","brown2","green12","blue9",
														       "red6","brown3","green13","blue10","red7","brown4","green1","blue11",
															   "red8","brown5","green2","blue12","red9","brown6","green3","blue13",
															   "red10","brown7","green4","blue1","red11","brown8","green5","blue2",
															   "red12","brown9","green6","blue3","red13","brown10","green7","blue4",
															   "red1","brown11","green8","blue5","red2","brown12","green9","blue6",
															   "red3","brown13","brown14","brown15","brown16","brown17","brown18","brownEnd"];
		
		private static const greenRoute:Array = ["brown4","green1","blue11","red8","brown5","green2","blue12","red9",
														      "brown6","green3","blue13","red10","brown7","green4","blue1","red11",
															  "brown8","green5","blue2","red12","brown9","green6","blue3","red13",
															  "brown10","green7","blue4","red1","brown11","green8","blue5","red2",
															  "brown12","green9","blue6","red3","brown13","green10","blue7","red4",
															  "brown1","green11","blue8","red5","brown2","green12","blue9","red6",
															  "brown3","green13","green14","green15","green16","green17","green18","greenEnd"];
		
		private static const redFlyPoint:Array = ["red1","red2","red3","red4","red5","red6","red7","red8","red9","red10","red11","red12"];
		private static const blueFlyPoint:Array = ["blue1","blue2","blue3","blue4","blue5","blue6","blue7","blue8","blue9","blue10","blue11","blue12"];
		private static const brownFlyPoint:Array = ["brown1","brown2","brown3","brown4","brown5","brown6","brown7","brown8","brown9","brown10","brown11","brown12"];
		private static const greenFlyPoint:Array = ["green1","green2","green3","green4","green5","green6","green7","green8","green9","green10","green11","green12"];
		
		private static const redPlane:Array =["redPlane1","redPlane2","redPlane3","redPlane4"];
		private static const bluePlane:Array = ["bluePlane1","bluePlane2","bluePlane3","bluePlane4"];
		private static const greenPlane:Array = ["greenPlane1","greenPlane2","greenPlane3","greenPlane4"];
		private static const brownPlane:Array = ["brownPlane1","brownPlane2","brownPlane3","brownPlane4"];
		
		
		private static const turnArray:Array = [{pos:"redReady",rot:90},{pos:"brownReady",rot:180},{pos:"greenRead",rot:-90},
																	{pos:"blueReady",rot:0}]
		
		private var flyRoute:Array = new Array();  //飞机飞行路径
		private var roomList:Array = ["room1","room2","room3","room4"]; //只允许有4个房间
		
		//*******************舞台元件*******************//
		/*private var redPlane1:MovieClip;
		private var redPlane2:MovieClip;
		private var redPlane3:MovieClip;
		private var redPlane4:MovieClip;
		
		private var bluePlane1:MovieClip;
		private var bluePlane2:MovieClip;
		private var bluePlane3:MovieClip;
		private var bluePlane4:MovieClip;
		
		private var greenPlane1:MovieClip;
		private var greenPlane2:MovieClip;
		private var greenPlane3:MovieClip;
		private var greenPlane4:MovieClip;
		
		private var brownPlane1:MovieClip;
		private var brownPlane2:MovieClip;
		private var brownPlane3:MovieClip;
		private var brownPlane4:MovieClip;
		
		private var creatGame:MovieClip;
		private var btnClose:SimpleButton;
		private var btnMax:SimpleButton;
		private var btnMin:SimpleButton;
		private var btnMove:SimpleButton;
		private var dragBan:MovieClip;
		private var multiStart:MovieClip;
		private var startMc:MovieClip;
		
		private var throwNum:MovieClip;
		private var bg:MovieClip;
		
		private var blueCover:MovieClip;
		private var brownCover:MovieClip;
		private var countMc:MovieClip;
		private var dragBan_s:MovieClip;
		private var greenCover:MovieClip;
		private var playerInfo:MovieClip;
		private var redCover:MovieClip;
		private var throwCover:MovieClip;*/
		////////////////////////////////////////////////////
		
		
		
		private var currentPlane:Array = new Array();		//当前玩家所能操控的 在仓库里的飞机
		private var currentFirstPos:Array = new Array();  //4个飞机 在仓库  各自的坐标。
		
		private var myName:String = "abc";							//当前玩家的名字
		private var myId:String = "";									//当前玩家的ID
		
		private var currentEnter:String= "";						//当前颜色飞机 进入最后直道的拐角MC的名字
		private var currentStartFly:String= "";    				//当前起飞点MC名。
		private var currentEndPos:String = "";					//当前终点MC名
		private var currentTurn:Number=0;
		
		private var playerColor:String;                 //当前玩家所操控飞机的颜色；
		private var finalNum:Number=0;			  //骰子掷出的点数---即所要走的步数
		private var outName:String;
		private var isMyTurn:Boolean = false;    //是否轮到当前玩家
		private var countNumber:Number=0;    //计时显示
		private var myTimer:Timer;					 //计时器 
		private var outSidePlane:Array = new Array();  //当前能控制的不在仓库的飞机
		private var currentIndex:Number = -1;
		private var currentName:String;
		private var moveArray:Array = new Array();  //可移动的飞机和坐标成对存放
		//********color status**********//
		private var isRed:Boolean = false;
		private var isBlue:Boolean = false;
		private var isGreen:Boolean = false;
		private var isBrown:Boolean = false;
		//*******************************//
		private var currentMoveObj:Object = new Object(); //当前移动的飞机对象
		private var planeSpeed:Number = 0.05;  //飞机移动的速度
		private var targetX:Number;
		private var targetY:Number;
		private var dis:Number;
		private var moveTime:Timer;
		
		private var currentRoute:Array = new Array();    //当前行走路径
		private var currentFlyPoint:Array = new Array();//当前可以飞行跳跃的点
		
		
		private var flyPointName:String = "";     //虚线飞行起点
		private var reachPointName:String = "";//虚线飞行终点
		
		
		
		
		private var totalPlaneArray:Array = new Array();			//保存所有飞机的位置（停机坪不在内）
		private var playerList:Array = new Array(); 					//当前房间内玩家列表
		
		
		private var roomOnShow:Array = new Array()  			 //保存当前建立的房间列表
		
		
		private var isRoomOwner:Boolean = false;   //是否为房主
		private var currentRoomName:String ;  //玩家所在房间名
		
		private var nextPlayerName:String;    //下一个走棋的玩家名
		private var currentPlayerName:String;  //当前玩家名
		private var currentRoomLeader:String;//当前所在房间房猪名
		private var currentPlaneName:String;//当前需要运动的飞机名
		private var totalFirstPos:Array = new Array(); //存放所有飞机起始位置
		private var colorToChoose:Array = new Array(); //存放已选择的颜色
		private var roomName:String;
		private var enterRoomName:String;
		
		private var movex:Number;
		private var movey:Number;
		
		//**********function***********//
		public function initWidget():void{
			
			this.fireRemoteEvent("JOIN_GAME",null,null,true);
			if(space){
				FDebug.Init(this);
				space.stage.frameRate = 30;
				myName = space.avatarName 
				this.widgetName = FlashName;
				//space层添加侦听事件//
				this.space.addEventListener("JOIN_GAME",playerJoin);
				this.space.addEventListener("confirmJoin",confirmJoin);
				this.space.addEventListener("userList",getUserList);
				this.space.addEventListener("yourTurn",checkMyTurn);
				this.space.addEventListener("planePos",getPos);
				this.space.addEventListener("backPos",getBackPos);
				this.space.addEventListener("updataRoomList",updataRoomList);
				this.space.addEventListener("arrival",planeArrival);
				///////
			}
			
			if(ExternalInterface.available && this.space){
				myName = ExternalInterface.call("getAvatarName");
				myId = (ExternalInterface.call("getUserId"));
			}
			
			this.initGame();
		}
		
		private function checkMyTurn(e:WidgetEvent):void{
			myTurnBegin();
		}
		
		
		private function playerJoin(e:WidgetEvent):void{     //返回房间列表
			this.fireRemoteEvent("confirmJoin",{room:roomList,roomshow:roomOnShow},[e.data.fromUser],true);
		}
		
		
		
		private function confirmJoin(e:WidgetEvent):void{
			var data:WidgetEventData=e.data;
			var args:Object = e.data.args;
			
			roomList = args.room;
			roomOnShow = args.roomshow;
			
			listRoom();
		}
		
		
		private function listRoom():void{    //显示出房间
			var i:Number;
			
			for(i=0;i<roomOnShow.length;++i){
				creatGame[roomOnShow[i].currentRoomName].visible = true;
				creatGame[roomOnShow[i].currentRoomName].roomName.text  = roomOnShow[i].roomName;
			}
		}
		
		private function setPlayerName(str:String):String{
			if (str.toLowerCase().indexOf(guestSign)>-1) {
				str=str.substr(guestSign.length);
			}
			return str;
		}
		
		//窗口操作//
		
		
		private function min(e:MouseEvent):void{
			mask = null;
			dragBan_s.visible = false;
			btnMin.visible = false
			btnMax.visible = true;
		}
		
		private function max(e:MouseEvent):void{
			mask = dragBan_s;
			dragBan_s.visible = true;
			btnMin.visible = true;
			btnMax.visible = false;
		}
		
		private function moveStage(e:MouseEvent):void{
			this.startDrag(false);
		}
		private function stopStage(e:MouseEvent):void{
			this.stopDrag();
		}
		
		private function closeWin(e:MouseEvent):void{
			if(this.space){
				var temp:Object = this.space.widgets;
				var newWidgets:Object = new Object();
				for(var str:String in temp){
					if(str.indexOf(FlashName + ".swf")>(-1)){
						continue;
					}
					newWidgets[str] = temp[str];
				}
				this.space.widgets = newWidgets;
				this.space.dispatchEvent(new Event(FlashName));
				this.space.fireRemoteEvent(WidgetSpace.WIDGET_UNLOADED);
				var Root:MovieClip = MovieClip(this.root);
				this.space.removeChild(Root);
				
				//关闭flash，删除space上的侦听
				this.space.removeEventListener("JOIN_GAME",playerJoin);
				this.space.removeEventListener("confirmJoin",confirmJoin);
				this.space.removeEventListener("userList",getUserList);
				this.space.removeEventListener("yourTurn",checkMyTurn);
				this.space.removeEventListener("planePos",getPos);
				this.space.removeEventListener("backPos",getBackPos);
			}
		}
		////////////////////
		
		
		
		private function makeNum(e:MouseEvent):void{
			if(!isMyTurn) return;
			this.throwNum.play();
			myTimer.stop();
		}
		
		private function getNum(e:MouseEvent):void{
			
			if(!isMyTurn) return;
			this.throwNum.useHandCursor = false;
			throwCover.visible = true;
			
			var randomFrame1:Number =Math.floor((Math.random()*6+1)) ;
			this.throwNum.gotoAndStop(randomFrame1);
			finalNum = this.throwNum.currentFrame;
			checkIfOut();
			myTimer.removeEventListener("timer",beginCount);
			
		}
		
		private function checkIfOut():void{
			enablePlane();                       //注册飞机侦听事件，此时玩家可以操控飞机。
			throwCover.visible = true;		//打开骰子遮盖，此时骰子不可用
			
			if(finalNum >4 && currentPlane.length != 0){            //当掷出了5点以上（包括5点），同时仓库里有飞机
				enableCover();
			}else if(finalNum<5 && outSidePlane.length ==0){  //掷出点数小于5点，同时外面没有可以移动飞机。
				myTurnOver();
			}
		}
		
		//打开停机坪遮挡 
		private function enableCover():void{
			if(playerColor == "red"){
				redCover.visible = false;
			}else if(playerColor == "blue"){
				blueCover.visible = false;
			}else if(playerColor == "green"){
				greenCover.visible = false;
			}else if(playerColor == "brown"){
				brownCover.visible = false;
			}
		}
		//关闭停机坪遮挡
		private function disableCover():void{
			if(playerColor == "red"){
				redCover.visible = true;
			}else if(playerColor == "blue"){
				blueCover.visible = true;
			}else if(playerColor == "green"){
				greenCover.visible = true;
			}else if(playerColor == "brown"){
				brownCover.visible = true;
			}
		}
		//		添加单色4个飞机的侦听事件
		private function enablePlane():void{
			if(playerColor == "red"){
				redPlane1.buttonMode = true;
				redPlane2.buttonMode = true;
				redPlane3.buttonMode = true;
				redPlane4.buttonMode = true;
				redPlane1.useHandCursor = true;
				redPlane2.useHandCursor = true;
				redPlane3.useHandCursor = true;
				redPlane4.useHandCursor = true;
				redPlane1.addEventListener(MouseEvent.CLICK,outPort);
				redPlane2.addEventListener(MouseEvent.CLICK,outPort);
				redPlane3.addEventListener(MouseEvent.CLICK,outPort);
				redPlane4.addEventListener(MouseEvent.CLICK,outPort);
			}else if(playerColor == "blue"){
				bluePlane1.buttonMode = true;
				bluePlane2.buttonMode = true;
				bluePlane3.buttonMode = true;
				bluePlane4.buttonMode = true;
				bluePlane1.useHandCursor = true;
				bluePlane2.useHandCursor = true;
				bluePlane3.useHandCursor = true;
				bluePlane4.useHandCursor = true;
				bluePlane1.addEventListener(MouseEvent.CLICK,outPort);
				bluePlane2.addEventListener(MouseEvent.CLICK,outPort);
				bluePlane3.addEventListener(MouseEvent.CLICK,outPort);
				bluePlane4.addEventListener(MouseEvent.CLICK,outPort);
			}else if(playerColor == "green"){
				greenPlane1.buttonMode = true;
				greenPlane2.buttonMode = true;
				greenPlane3.buttonMode = true;
				greenPlane4.buttonMode = true;
				greenPlane1.useHandCursor = true;
				greenPlane2.useHandCursor = true;
				greenPlane3.useHandCursor = true;
				greenPlane4.useHandCursor = true;
				greenPlane1.addEventListener(MouseEvent.CLICK,outPort);
				greenPlane2.addEventListener(MouseEvent.CLICK,outPort);
				greenPlane3.addEventListener(MouseEvent.CLICK,outPort);
				greenPlane4.addEventListener(MouseEvent.CLICK,outPort);
			}else if(playerColor == "brown"){
				brownPlane1.buttonMode = true;
				brownPlane2.buttonMode = true;
				brownPlane3.buttonMode = true;
				brownPlane4.buttonMode = true;
				brownPlane1.useHandCursor = true;
				brownPlane2.useHandCursor = true;
				brownPlane3.useHandCursor = true;
				brownPlane4.useHandCursor = true;
				brownPlane1.addEventListener(MouseEvent.CLICK,outPort);
				brownPlane2.addEventListener(MouseEvent.CLICK,outPort);
				brownPlane3.addEventListener(MouseEvent.CLICK,outPort);
				brownPlane4.addEventListener(MouseEvent.CLICK,outPort);
			}
		}
		//删除单色4个飞机的侦听事件
		private function disablePlane():void{
			if(playerColor == "red"){
				redPlane1.useHandCursor = false;
				redPlane2.useHandCursor = false;
				redPlane3.useHandCursor = false;
				redPlane4.useHandCursor = false;
				redPlane1.removeEventListener(MouseEvent.CLICK,outPort);
				redPlane2.removeEventListener(MouseEvent.CLICK,outPort);
				redPlane3.removeEventListener(MouseEvent.CLICK,outPort);
				redPlane4.removeEventListener(MouseEvent.CLICK,outPort);
			}else if(playerColor == "blue"){
				bluePlane1.useHandCursor = false;
				bluePlane2.useHandCursor = false;
				bluePlane3.useHandCursor = false;
				bluePlane4.useHandCursor = false;
				bluePlane1.removeEventListener(MouseEvent.CLICK,outPort);
				bluePlane2.removeEventListener(MouseEvent.CLICK,outPort);
				bluePlane3.removeEventListener(MouseEvent.CLICK,outPort);
				bluePlane4.removeEventListener(MouseEvent.CLICK,outPort);
			}else if(playerColor == "green"){
				greenPlane1.useHandCursor = false;
				greenPlane2.useHandCursor = false;
				greenPlane3.useHandCursor = false;
				greenPlane4.useHandCursor = false;
				greenPlane1.removeEventListener(MouseEvent.CLICK,outPort);
				greenPlane2.removeEventListener(MouseEvent.CLICK,outPort);
				greenPlane3.removeEventListener(MouseEvent.CLICK,outPort);
				greenPlane4.removeEventListener(MouseEvent.CLICK,outPort);
			}else if(playerColor == "brown"){
				brownPlane1.useHandCursor = false;
				brownPlane2.useHandCursor = false;
				brownPlane3.useHandCursor = false;
				brownPlane4.useHandCursor = false;
				brownPlane1.removeEventListener(MouseEvent.CLICK,outPort);
				brownPlane2.removeEventListener(MouseEvent.CLICK,outPort);
				brownPlane3.removeEventListener(MouseEvent.CLICK,outPort);
				brownPlane4.removeEventListener(MouseEvent.CLICK,outPort);
			}
		}
		
		//飞机出仓以及移动
		private function outPort(e:MouseEvent):void{
			if(!isMyTurn) return;
			disablePlane();
			currentPlaneName = e.currentTarget.name;
			this.throwNum.useHandCursor = true;
			if(outSidePlane.indexOf(currentPlaneName,0) == -1){   //飞机还在仓库,飞机出仓。
				//trace("out");
				outSidePlane.push(currentPlaneName);
				var index:Number = currentPlane.indexOf(currentPlaneName);
				currentPlane.splice(index,1);
				//e.currentTarget.x = getChildByName(currentStartFly).x;
				//e.currentTarget.y = getChildByName(currentStartFly).y;
				currentName = currentStartFly;
				
				targetX = this.getChildByName(currentName).x;
				targetY = this.getChildByName(currentName).y;
				
				currentMoveObj = e.currentTarget;
				
				moveArray.push({planename:currentPlaneName,planepos:currentIndex});
				this.fireRemoteEvent("planePos",{planeName:currentPlaneName,currentName:currentName},playerList,true);
				movex = targetX - currentMoveObj.x;
				movey =	targetY - currentMoveObj.y;
				
				//var index3:Number = turnArray.indexOf(currentName,0);
				//var rota:Number = turnArray[index3].rot;
				
				var q:Number  ;
				var rota:Number;
				for(q=0;q<turnArray.length;q++){
					if(turnArray[q].pos == currentName){
						rota = turnArray[q].rot;
					}
				}
				
				currentMoveObj.rotation = rota;
				
				moveTime= new Timer(30);
				moveTime.addEventListener(TimerEvent.TIMER,planeMove);
				moveTime.start();
				checkMoreThrow();
				
			}else{														//已出仓de飞机移动
				var i:Number;
				
				//trace(moveArray.length);
				for(i=0;i<moveArray.length;i++)
				{
					//trace(moveArray[i].planename);
					if(moveArray[i].planename ==currentPlaneName)  
					{						
						moveArray[i].planepos = moveArray[i].planepos + finalNum;
						
						//flyRoute = 1;
						//***飞机到达终点***//
						if(moveArray[i].planepos > 54)
						{
							//trace("arrival");
							this.arrival();
							this.fireRemoteEvent("arrival",{planeName:currentPlaneName},playerList,true);
							//removeChild(MovieClip(e.currentTarget));
							//var index1:int = outSidePlane.indexOf(e.currentTarget.name);
							//outSidePlane.splice(index1,1);
							return;
						}
						/////////////////////
						
						flyRoute = currentRoute.slice(moveArray[i].planepos - finalNum+1,moveArray[i].planepos+1);
						
						FDebug.msg(flyRoute.toString());
						
						currentName = currentRoute[moveArray[i].planepos].toString();						
						
						if(currentFlyPoint.indexOf(currentName)!=-1)
						{
							if(currentName ==flyPointName)
							{
								currentName = reachPointName;
								moveArray[i].planepos = 29;
								
								checkTurn();
								
								//current
							}
							else
							{
								if(currentName == currentFlyPoint[currentFlyPoint.length - 1])   //飞行点的最后1个
								{
									currentName = currentEnter;
								}
								else
								{
									currentName = currentFlyPoint[currentFlyPoint.indexOf(currentName)+1];
								}
								//到达下一个飞行点后，判断 是否为虚线飞行起点，如是，继续飞
								if(currentName == flyPointName)
								{
									currentName =	reachPointName;
									moveArray[i].planepos = 29;
								}
								else
								{
									moveArray[i].planepos = moveArray[i].planepos + 4;
								}
							}
						}
					}
				}
				
				//trace("dangqian",currentName);
				targetX = this.getChildByName(currentName).x;
				targetY = this.getChildByName(currentName).y;
				currentMoveObj =e.currentTarget;
				/*var j:Number;
				for(j=0;j<totalPlaneArray.length;j++){
					if(totalPlaneArray[j].planename == e.currentTarget.name){
						totalPlaneArray[j].planepos = currentName;
					}
				}*/
				//FDebug.msg("planeName1111"+ e.currentTarget.name)
				this.fireRemoteEvent("planePos",{planeName:e.currentTarget.name,currentName:currentName},playerList,true);
				
				movex = targetX - currentMoveObj.x;
				movey =	targetY - currentMoveObj.y;
				
				moveTime= new Timer(30);
				moveTime.addEventListener(TimerEvent.TIMER,planeMove);
				moveTime.start();
				checkMoreThrow();
			}
			
			outName = e.currentTarget.name;
			disableCover();
		}
	
	
		private function checkTurn(){
			var disX:Number = this.getChildByName(flyPointName).x - this.getChildByName(reachPointName).x;
			var disY:Number = this.getChildByName(flyPointName).y - this.getChildByName(reachPointName).y;
			
			if(disX>3) 	 		currentTurn = -90; //X轴反方向，-90；
			if(disY>3)  		currentTurn = 180;//Y轴反方向，180；
			if(disX<-3)		currentTurn = 90;//X轴正方向，90；
			if(disY<-3)		currentTurn = 0;//Y轴正方向，0；
			
		}
		private function planeArrival(e:WidgetEvent):void{
			currentPlaneName = e.data.args.planeName;
			currentMoveObj = this.getChildByName(currentPlaneName);
			this.arrival();
		}
		
		private function arrival(){
			
		}
		
		private function getPos(e:WidgetEvent):void{
			currentPlaneName = e.data.args.planeName;
			currentName = e.data.args.currentName;
			
			targetX = this.getChildByName(currentName).x;
			targetY = this.getChildByName(currentName).y;
			
			currentMoveObj = this.getChildByName(currentPlaneName);
			
			var totalLength:Number = totalPlaneArray.length;
			var totalNumber:Number = 0;
			
			if(totalLength == 0 ){
				totalPlaneArray.push({planename:currentPlaneName,planepos:currentName});
			}else{
				var j:Number;
			
				for(j=0;j<totalLength;j++){
					if(totalPlaneArray[j].planename==currentPlaneName){
						totalPlaneArray[j].planepos = currentName;
						totalNumber++;
					}
				}
				if(totalNumber == 0)
					totalPlaneArray.push({planename:currentPlaneName,planepos:currentName});
			}
			
			movex = targetX - currentMoveObj.x;
			movey =	targetY - currentMoveObj.y;
			moveTime = new Timer(30);
			moveTime.addEventListener(TimerEvent.TIMER,planeMove);
			moveTime.start();
		}
		
		
		
		//飞机飞行动画
		private function planeMove(e:TimerEvent):void{
			/*var movex:Number = this.getChildByName(currentName).x - currentMoveObj.x;
			var movey:Number = this.getChildByName(currentName).y - currentMoveObj.y;*/
			
			
			var p1:Point = new Point(targetX,targetY);
			var p2:Point = new Point(currentMoveObj.x ,currentMoveObj.y);
			
			dis = Point.distance(p1,p2);
			if(dis<3){
					currentMoveObj.x = targetX;
					currentMoveObj.y = targetY;
					moveTime.stop();
					checkDestroy();
					//if(isMyTurn)
						//checkMoreThrow();
			}else{
					var vx:Number = movex*planeSpeed;
					var vy:Number = movey*planeSpeed;
					
					currentMoveObj.x +=  vx;
					currentMoveObj.y += vy;
			}
			
		}
		
		private function checkMoreThrow():void{
			//trace(finalNum);
			if(!isMyTurn) return; 
			if(finalNum == 6){
				countTime();
				throwCover.visible = false;
			}else{
				myTurnOver();
			}
		}
		
		//游戏开始，玩家选择颜色
		private function chooseColor(e:MouseEvent):void{
			this.startMc.brownk.x = e.currentTarget.x;
			this.startMc.brownk.y = e.currentTarget.y;
			this.startMc.brownk.visible = true;
			playerColor = e.currentTarget.name;
			
			if(isRoomOwner){
				this.startMc.startGame.addEventListener(MouseEvent.CLICK,readyToStart);
			}else{   //不是房主
				this.startMc.startGame.addEventListener(MouseEvent.CLICK,waitToStart);
			}
		}
		
		private function updataColor(e:WidgetEvent):void{
			colorToChoose = e.data.args.colorA;
		}
		
		private function waitToStart(e:MouseEvent):void{
			colorToChoose.push(playerColor);
			confirmRoute();
			
			recordFirstPos(playerColor);
			
			this.fireRemoteEvent("updataColor",{colorA:colorToChoose},[currentRoomLeader],true);
			this.throwCover.visible = true;
			this.startMc.visible = false;
			multiStart.visible = false;
		}
		
		//only for roomowner;	
		private function readyToStart(e:MouseEvent):void{
			if(!isRoomOwner) return;
			colorToChoose.push(playerColor);
			confirmRoute();
			
			recordFirstPos(playerColor);
			this.startMc.visible = false;
			multiStart.x = bg.width/2 - multiStart.width/2;
			multiStart.y = bg.height/2 - multiStart.height/2;
			multiStart.visible = true;
			multiStart.gotoAndStop(2);
			multiStart.multiCover.visible = true;
			currentRoomName = roomList.shift();    
			currentPlayerName = myName;
			currentRoomLeader = myName;
			playerList.push(myName);
			roomName = currentRoomLeader + "'s room"
			roomOnShow.push({currentRoomName:currentRoomName,roomName:roomName}); 
			if(space){
				this.space.addEventListener("JOIN_ROOM",comfirmJoinRoom);   //如为房主，添加侦听加入房间事件
				this.space.addEventListener("myTurnOver",getNextTurn);
				this.space.addEventListener("updataColor",updataColor);
			}
			this.fireRemoteEvent("updataRoomList",{room:roomList,roomshow:roomOnShow},null,true);
		}
		
		//确定当前飞行路线数组
		private function confirmRoute():void{
			if(playerColor == "red"){
				currentRoute = redRoute;
				currentFlyPoint = redFlyPoint;
				flyPointName = "red5";
				reachPointName = "red8";
				currentEnter = "red13";
				currentPlane = redPlane;
				currentStartFly = "redReady";
				currentEndPos = "redEnd";
			}else if(playerColor == "blue"){
				currentRoute = blueRoute;
				currentFlyPoint = blueFlyPoint;
				flyPointName = "blue5";
				reachPointName = "blue8";
				currentEnter = "blue13";
				currentPlane = bluePlane;
				currentStartFly = "blueReady";
				currentEndPos="blueEnd";
			}else if(playerColor == "green"){
				currentRoute =greenRoute;
				currentFlyPoint = greenFlyPoint;
				flyPointName = "green5";
				reachPointName = "green8";
				currentEnter = "green13";
				currentPlane = greenPlane;
				currentStartFly = "greenReady";
				currentEndPos = "greenEnd";
			}else if(playerColor == "brown"){
				currentRoute = brownRoute;
				currentFlyPoint = brownFlyPoint;
				flyPointName = "brown5";
				reachPointName = "brown8";
				currentEnter = "brown13";
				currentPlane = brownPlane;
				currentStartFly = "brownReady";
				currentEndPos = "brownEnd";
			}
		}
		
		//确定飞机在仓库中的初始位置
		private function recordFirstPos(color:String):void{
			totalFirstPos.push({planename:"redPlane1",planeposx:redPlane1.x,planeposy:redPlane1.y});
			totalFirstPos.push({planename:"redPlane2",planeposx:redPlane2.x,planeposy:redPlane2.y});
			totalFirstPos.push({planename:"redPlane3",planeposx:redPlane3.x,planeposy:redPlane3.y});
			totalFirstPos.push({planename:"redPlane4",planeposx:redPlane4.x,planeposy:redPlane4.y});
			totalFirstPos.push({planename:"bluePlane1",planeposx:bluePlane1.x,planeposy:bluePlane1.y});
			totalFirstPos.push({planename:"bluePlane2",planeposx:bluePlane2.x,planeposy:bluePlane2.y});
			totalFirstPos.push({planename:"bluePlane3",planeposx:bluePlane3.x,planeposy:bluePlane3.y});
			totalFirstPos.push({planename:"bluePlane4",planeposx:bluePlane4.x,planeposy:bluePlane4.y});
			totalFirstPos.push({planename:"greenPlane1",planeposx:greenPlane1.x,planeposy:greenPlane1.y});
			totalFirstPos.push({planename:"greenPlane2",planeposx:greenPlane2.x,planeposy:greenPlane2.y});
			totalFirstPos.push({planename:"greenPlane3",planeposx:greenPlane3.x,planeposy:greenPlane3.y});
			totalFirstPos.push({planename:"greenPlane4",planeposx:greenPlane4.x,planeposy:greenPlane4.y});
			totalFirstPos.push({planename:"brownPlane1",planeposx:brownPlane1.x,planeposy:brownPlane1.y});
			totalFirstPos.push({planename:"brownPlane2",planeposx:brownPlane2.x,planeposy:brownPlane2.y});
			totalFirstPos.push({planename:"brownPlane3",planeposx:brownPlane3.x,planeposy:brownPlane3.y});
			totalFirstPos.push({planename:"brownPlane4",planeposx:brownPlane4.x,planeposy:brownPlane4.y});
			if(color == "red"){
				currentFirstPos.push({planename:"redPlane1",planeposx:redPlane1.x,planeposy:redPlane1.y});
				currentFirstPos.push({planename:"redPlane2",planeposx:redPlane2.x,planeposy:redPlane2.y});
				currentFirstPos.push({planename:"redPlane3",planeposx:redPlane3.x,planeposy:redPlane3.y});
				currentFirstPos.push({planename:"redPlane4",planeposx:redPlane4.x,planeposy:redPlane4.y});
			}else if(color == "blue"){
				currentFirstPos.push({planename:"bluePlane1",planeposx:bluePlane1.x,planeposy:bluePlane1.y});
				currentFirstPos.push({planename:"bluePlane2",planeposx:bluePlane2.x,planeposy:bluePlane2.y});
				currentFirstPos.push({planename:"bluePlane3",planeposx:bluePlane3.x,planeposy:bluePlane3.y});
				currentFirstPos.push({planename:"bluePlane4",planeposx:bluePlane4.x,planeposy:bluePlane4.y});
			}else if(color == "green"){
				currentFirstPos.push({planename:"greenPlane1",planeposx:greenPlane1.x,planeposy:greenPlane1.y});
				currentFirstPos.push({planename:"greenPlane2",planeposx:greenPlane2.x,planeposy:greenPlane2.y});
				currentFirstPos.push({planename:"greenPlane3",planeposx:greenPlane3.x,planeposy:greenPlane3.y});
				currentFirstPos.push({planename:"greenPlane4",planeposx:greenPlane4.x,planeposy:greenPlane4.y});
			}else if(color == "brown"){
				currentFirstPos.push({planename:"brownPlane1",planeposx:brownPlane1.x,planeposy:brownPlane1.y});
				currentFirstPos.push({planename:"brownPlane2",planeposx:brownPlane2.x,planeposy:brownPlane2.y});
				currentFirstPos.push({planename:"brownPlane3",planeposx:brownPlane3.x,planeposy:brownPlane3.y});
				currentFirstPos.push({planename:"brownPlane4",planeposx:brownPlane4.x,planeposy:brownPlane4.y});
			}
		}
		
		
		//游戏开始 for owner;
		private function startGame(e:MouseEvent):void{
			this.startMc.visible = false;
			//isMyTurn = true;
			multiStart.visible = false;
			
			
			if(myName == playerList[0] && playerList.length != 0){
				//this.fireRemoteEvent("startGame",null,null,true);
				myTurnBegin();
				countTime();
			}else{
				//this.space.addEventListener("startGame",playerStart);
			}
			
			
		}
		
		private function playerStart(e:WidgetEvent):void{ 
				throwCover.visible = true;		
				isMyTurn = false;
				disableCover();
				disablePlane();
		}
		
		
		private function countTime():void{
			countMc.countTxt.text = "00";
			countNumber = 0;
			myTimer= new Timer(1000);
			myTimer.start();
			myTimer.addEventListener("timer",beginCount);
		}
		
		private function beginCount(e:TimerEvent):void{
			countNumber ++;
			if(countNumber <10){
				countMc.countTxt.text = "0" + String(countNumber);
			}else{
				countMc.countTxt.text = String(countNumber);
			}
			if(countNumber==60) {
				myTimer.stop();
				myTimer.removeEventListener("timer",beginCount);
				autoThrow();
				myTurnOver();
			}
		}
		
		private function myTurnBegin():void{
			//this.space.fireRemoteEvent(""
			throwCover.visible = false;
			isMyTurn = true;
			//enableCover();
			//enablePlane();
		}
		
		private function autoThrow():void{    //当玩家超时，自动掷骰子。
			this.throwNum.play();
			var randomFrame:Number =Math.floor((Math.random()*6+1)) ;
			this.throwNum.gotoAndStop(randomFrame);
			finalNum = this.throwNum.currentFrame;
			
			var randomPlane:String = new String();
			
			if(finalNum >4 && currentPlane.length!=0){ 
				randomPlane = currentPlane[Math.floor(Math.random()*currentPlane.length)]
				
				this.getChildByName(randomPlane).x = this.getChildByName(currentStartFly).x
				this.getChildByName(randomPlane).y = this.getChildByName(currentStartFly).y
			}else if(finalNum<4 && outSidePlane.length == 0){
				//没有飞机在外面 ,什么都不做。。。。
			}else{
				trace(finalNum,outSidePlane);
				randomPlane = outSidePlane[Math.floor(Math.random()*outSidePlane.length)];
			
				//this.getChildByName(randomPlane).x = this.getChildByName(currentStartFly).x
				//this.getChildByName(randomPlane).y = this.getChildByName(currentStartFly).y
			}
			
			//trace(randomPlane);
		}
		
		//本回合结束
		private function myTurnOver():void{
			if(isRoomOwner){
				isMyTurn = false;
				throwCover.visible = true;
				this.getNextPlayer();
				disableCover();
				disablePlane();
			}else{
				isMyTurn= false;
				throwCover.visible = true;
				disableCover();
				disablePlane();
				this.fireRemoteEvent("myTurnOver",null,[currentRoomLeader],true);
			}
		}
		
		private function getNextPlayer():void{  // 由房主来控制当前房间走棋顺序并派发消息
			if(!isRoomOwner)return;
			
			var playerIndex:Number = playerList.indexOf(currentPlayerName);
			playerIndex++;
			
			//FDebug.msg("playerIndex",playerIndex);
			if(playerIndex>playerList.length -1){
				playerIndex = 0;
				myTurnBegin();
				//return;
			}
			currentPlayerName = playerList[playerIndex];
			//FDebug.msg("playerIndex after",playerIndex,"currentPlayerName",currentPlayerName);
			this.fireRemoteEvent("yourTurn",{name:currentPlayerName},[currentPlayerName],true);
		}
		
		//检查 在相同位置是否发生碰撞
		private function checkDestroy():void{
			
			//this.fireRemoteEvent("totalPlaneArray length"+totalPlaneArray.length);
			
			var totalLength:Number = totalPlaneArray.length;
			
			//FDebug.msg("========");
			//FDebug.msg("totalPlaneArray"+totalPlaneArray);
			if( totalLength == 0) return;
			
			var m:Number;
			
			/*FDebug.msg("showtotalPlaneArray length::::"+totalLength);
			FDebug.msg("showcurrentName::::::"+currentName);*/
			
			//this.fireRemoteEvent("totalPlaneArray"+totalPlaneArray.toString());
			for(m=0;m< totalLength;++m)
			{
				
				
				FDebug.msg("forcurrentName:::::"+currentName);
				FDebug.msg("forcurrentPos:::::"+ totalPlaneArray[m].planepos);
				if(currentName == totalPlaneArray[m].planepos)
				{
					//检验碰撞 飞机回仓
					
					currentPlaneName = totalPlaneArray[m].planename;
					FDebug.msg(currentPlaneName+" back to the airport");
					var firstPosIndex:Number = totalFirstPos.indexOf(currentPlaneName,0);
					this.getChildByName(currentPlaneName).x = totalFirstPos[firstPosIndex].planeposx;
					this.getChildByName(currentPlaneName).y = totalFirstPos[firstPosIndex].planeposy;
					totalPlaneArray.splice(m,1)
					this.fireRemoteEvent("backPos",{planeName:currentPlaneName,planeposx:totalFirstPos[firstPosIndex].planeposx,planeposy:totalFirstPos[firstPosIndex].planeposy},playerList,true);
					//this.fireRemoteEvent("planePos"
				}
			}
		}
		
		
		//飞机回仓
		private function getBackPos(e:WidgetEvent):void{
			currentPlaneName = e.data.args.planeName;
			
			this.getChildByName(currentPlaneName).x = e.data.args.planeposx;
			this.getChildByName(currentPlaneName).y = e.data.args.planeposy;
			//将飞机名和坐标从 仓外飞机列表中删除
			//totalPlaneArray
		}
		//游戏初始化
		private function initGame():void{
			playerInfo.visible = false;
			btnMin.visible = false;
			startMc.visible = false;
			multiStart.visible = false;
			creatGame.x = bg.width/2 - creatGame.width/2;
			creatGame.y = bg.height/2 - creatGame.height/2;
			this.startMc.brownk.visible = false;
			startMc.x = bg.width/2 - startMc.width/2;
			startMc.y = bg.height/2 - startMc.height/2;
			countMc.countTxt.text = "00";
			throwCover.visible = true;
			//this.creatGame.singleBtn.addEventListener(MouseEvent.CLICK,singlePlay);
			this.creatGame.creatBtn.addEventListener(MouseEvent.CLICK,creatRoom);
			
			this.creatGame.room1.roomEnter.addEventListener(MouseEvent.CLICK,enterRoom);
			this.creatGame.room2.roomEnter.addEventListener(MouseEvent.CLICK,enterRoom);
			this.creatGame.room3.roomEnter.addEventListener(MouseEvent.CLICK,enterRoom);
			this.creatGame.room4.roomEnter.addEventListener(MouseEvent.CLICK,enterRoom);
			
			this.creatGame.room1.visible = false;
			this.creatGame.room2.visible = false;
			this.creatGame.room3.visible = false;
			this.creatGame.room4.visible = false;
			
			this.startMc.brown.addEventListener(MouseEvent.CLICK,chooseColor);
			this.startMc.green.addEventListener(MouseEvent.CLICK,chooseColor);
			this.startMc.red.addEventListener(MouseEvent.CLICK,chooseColor);
			this.startMc.blue.addEventListener(MouseEvent.CLICK,chooseColor);
			
			this.btnMin.addEventListener(MouseEvent.CLICK,min);
			this.btnMax.addEventListener(MouseEvent.CLICK,max);
			this.btnMove.addEventListener(MouseEvent.MOUSE_DOWN,moveStage);
			this.btnMove.addEventListener(MouseEvent.MOUSE_UP,stopStage);
			this.dragBan.addEventListener(MouseEvent.MOUSE_DOWN,moveStage);
			this.dragBan.addEventListener(MouseEvent.MOUSE_UP,stopStage);
			this.btnClose.addEventListener(MouseEvent.CLICK,closeWin);
			
			this.throwNum.addEventListener(MouseEvent.MOUSE_DOWN,makeNum);
			this.throwNum.addEventListener(MouseEvent.MOUSE_UP,getNum);
			this.throwNum.gotoAndStop(0);
			this.throwNum.buttonMode = true;
			this.throwNum.useHandCursor = true;
			
			disableCover();
			disablePlane();
		}
		
		
		//单人游戏
		private function singlePlay(e:MouseEvent):void{
			creatGame.visible = false;
			this.startMc.visible = true;
			
		}
		
		//创建多人游戏房间
		private function creatRoom(e:MouseEvent):void{
			if(roomList.length !=0){
				isRoomOwner =  true;
				this.startMc.visible = true;
				creatGame.visible = false;
			}
		}
		
		private function updataRoomList(e:WidgetEvent):void{   //更新房间列表
			var data:WidgetEventData=e.data;
			var args:Object = e.data.args;
			
			roomList = args.room;
			roomOnShow = args.roomshow;
			//colorToChoose = args.chosenColor;
			
			listRoom();
		}
		
		private function getNextTurn(e:WidgetEvent):void{
			this.getNextPlayer();
			
			FDebug.msg("getNextTurn")
		}
		
		private function comfirmJoinRoom(e:WidgetEvent):void{
			if(currentRoomName == e.data.args.room && isRoomOwner){        //如果为房主，判断发来的房间名 是否为自己创建的 
				playerList.push(e.data.fromUser)
				this.fireRemoteEvent("userList",{userList:playerList,colorB:colorToChoose},[e.data.fromUser],true)      //发送当前房间玩家列表
				this.multiStart.multiCover.visible = false;
				this.multiStart.gotoAndStop(1);
				this.multiStart.ownerBtn.addEventListener(MouseEvent.CLICK,startGame);
			}
		}
		
		private function getUserList(e:WidgetEvent):void{       //刷新当前房间玩家列表名单
		
			currentRoomLeader = e.data.fromUser;           //确认房主
			playerList = e.data.args.userList;						
			colorToChoose = e.data.args.colorB;
			
			var i:Number;
			
			for(i = 0;i<colorToChoose.length;i++){
				this.startMc[colorToChoose[i]].visible = false;
			}
			
		}
		
		//进入房间
		private function enterRoom(e:MouseEvent):void{
			isRoomOwner = false;
			this.startMc.visible = true;
			creatGame.visible = false;
			currentRoomName = e.currentTarget.name;
			enterRoomName = e.currentTarget.parent.name;
			this.fireRemoteEvent("JOIN_ROOM",{room:e.currentTarget.parent.name},null,true); //告诉房主们 我进了哪个房间
			
		}
		//////////////////////////////////////////////
	}
}